package com.qire.manhua.controller;

import android.graphics.Typeface;
import android.view.View;
import android.widget.TextView;

import com.google.android.material.appbar.AppBarLayout;
import com.ogaclejapan.smarttablayout.SmartTabLayout;
import com.qire.antsrouter.AntsRouter;
import com.qire.antsrouter.card.FloorCard;
import com.qire.common.basic.ObjectUtil;
import com.qire.common.constant.AdvertManage;
import com.qire.common.constant.Navigation;
import com.qire.common.model.entity.UserEntity;
import com.qire.common.support.base.EventController;
import com.qire.common.utils.EquipmentInfoUtil;
import com.qire.common.utils.ToastHelper;
import com.qire.manhua.activity.ComicDetailActivity;
import com.qire.manhua.activity.helper.LoginRouter;
import com.qire.manhua.dialog.MessageEnablePromptDialog;
import com.qire.manhua.dialog.ShareComicDialog;
import com.qire.manhua.dialog.UnlockChapterOnComicDetailDialog;
import com.qire.manhua.model.entity.ComicBookEntity;
import com.qire.manhua.model.entity.ComicBookEntity.DirectoryInfo;
import com.qire.manhua.model.viewModel.impl.ComicDetailViewModel;
import com.qire.manhua.model.viewModel.impl.UnlockChapterDialogViewModel;
import com.qire.other.recorder.ComicActionRecorder;

import androidx.annotation.NonNull;

public class ComicDetailController extends EventController<ComicDetailActivity> implements ComicDetailUnlockController {

    private ComicDetailViewModel viewModel;

//    private MobShareHelper mobShareHelper;

    public ComicDetailController(@NonNull ComicDetailActivity lifecycleOwner) {
        super(lifecycleOwner);
    }

    @Override
    protected void bindView() {
        owner.viewDataBinder().setComicDetailController(this);
    }

    @Override
    protected void onCleared() {
        super.onCleared();
        this.viewModel = null;
//        if(mobShareHelper != null){
//            mobShareHelper.destroy();
//        }
    }

    public void onAddition(ComicDetailViewModel viewModel) {
        this.viewModel = viewModel;
    }

    /*************************************************************************************************************************/

    /** 返回按钮单击事件**/
    public void backBtnOnClick(View view){
        owner.onBackPressed();
    }

    /** 会员免费阅读提示板单击事件**/
    public void openVipFreeReadTipPlateOnClick(View view){
        viewModel.showVipFreeTipsDialog(this);// 跳转开通会员
    }

    /**
     * 免费提示窗口---加入会员按钮事件
     */
    public void joinMembershipBtnOnClick(View view) {
        AntsRouter.ROUTER.buildCard(Navigation.Page.BuyMembershipPage).navigation();
    }

    /** 收藏按钮单击事件**/
    public void whetherCollectionBtnOnClick(View view) {
        if(LoginRouter.ROUTER.checkLoginRouteIfNeed()) {
            return;
        }
        viewModel.whetherToFavorites();

        MessageEnablePromptDialog.showIfNeed(view.getContext());
    }


    /** 分享按钮单击事件**/
    public void shareBtnOnClick(View view) {
        new ShareComicDialog(view.getContext(), viewModel.shareInfo()).show();

        ComicBookEntity comicBookEntity = viewModel.comicBookEntity();
        if(ObjectUtil.nonNull(comicBookEntity)) {
            // 行为数据统计
            ComicActionRecorder.build(ComicActionRecorder.count_share)
                    .putParam("分享位置", "详情页")
                    .setComicInfo(comicBookEntity.id, comicBookEntity.bookName)
                    .doRecorde(view.getContext());
        }
    }

    /** 下载按钮单击事件**/
    public void downloadBtnOnClick(View view) {
        ComicBookEntity comicBookEntity = viewModel.comicBookEntity();
        if(ObjectUtil.isNull(comicBookEntity)) {
            ToastHelper.showToast("漫画书数据有误");
            return;
        }

        AntsRouter.ROUTER.<FloorCard>buildCard(Navigation.Page.ComicDownloadSelectorPage)
                .withData("comicBookEntity", comicBookEntity)
                .navigation();

        // 行为数据统计
        ComicActionRecorder.build(ComicActionRecorder.count_down)
                .setSource("详情页")
                .setComicInfo(comicBookEntity.id, comicBookEntity.bookName)
                .doRecorde(view.getContext());
    }

    /** 开始阅读按钮单击事件**/
    public void readBtnOnClick(View view) {
        ComicBookEntity comicBookEntity = viewModel.comicBookEntity();
        if(ObjectUtil.isNull(comicBookEntity)) {
            ToastHelper.showToast("漫画未加载，请稍候重新进入！");
            return;
        }

        DirectoryInfo lastReadDirectory = comicBookEntity.defReadingDirectoryInfo();
        if(ObjectUtil.nonNull(lastReadDirectory)) {
            // 阅读最后一次阅读章节
            comicBookEntity.chaptersReading(lastReadDirectory.chapterId);
            // 拦截未解锁的章节
            if(lastReadDirectory.haveLock()) {
                UnlockChapterDialogViewModel unlockDialogViewModel = new UnlockChapterDialogViewModel();
                unlockDialogViewModel.loadComicData(comicBookEntity, lastReadDirectory);

                boolean noInsufficientBalance = !unlockDialogViewModel.isInsufficientBalanceByPanel();
                boolean isAutoUnlock = UserEntity.self.isAutoPay();
                if(!(noInsufficientBalance && isAutoUnlock)) {
                    UnlockChapterOnComicDetailDialog.build(owner, unlockDialogViewModel, this).show();
                    return;
                }
            }
        }

        AntsRouter.ROUTER.<FloorCard>buildCard(Navigation.Page.ComicReaderPage)
                .withData("comicBookEntity", comicBookEntity)
                .navigation();
    }

    /** 头部联动行为改变监听*/
    public void appBarOnOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
        float offset = verticalOffset * -1.0f / appBarLayout.getTotalScrollRange();
        viewModel.setCoverLayerAlpha(offset);
    }

    /** 子页面左右滑动监听*/
    public void viewPagerOnPageSelected(int position) {
        SmartTabLayout comicDetailTabLayout = owner.viewDataBinder().comicDetailTabLayout;
        for(int index = 0; index < 2; index++) {
            View tabText = comicDetailTabLayout.getTabAt(index);
            if(tabText != null) {
                ((TextView) tabText).setTypeface(position == index ? Typeface.DEFAULT_BOLD : Typeface.DEFAULT);
            }
        }
    }

    @Override
    public void unlockByAdBtnOnClick(View view) {
        UnlockChapterDialogViewModel unlockChapterViewModel = ObjectUtil.as(view.getTag(), UnlockChapterDialogViewModel.class);
        if(ObjectUtil.nonNull(unlockChapterViewModel)) {
            final int chapterId = unlockChapterViewModel.getChapterId();
            viewModel.showLoadDialog();
            AdvertManage.AdvertSpace.ComicUnlock.build()
                    .setSize(EquipmentInfoUtil.getScreenWidth(), 0)
//                    .setClosedListener(() -> ToastHelper.showToast("您取消了视频播放，放弃了解锁奖励！"))
                    .setClosedListener(() -> viewModel.unlockChapterByAd(chapterId))
                    .setErrorListener(() -> {
                        viewModel.dismissLoadDialog();
                        ToastHelper.showToast("运行错误，请联系客服或稍后再试！");
                    })
                    .setStartListener(viewModel::dismissLoadDialog)
                    .playVideo(owner);
        }
    }

    @Override
    public void unlockByBuyBtnOnClick(View view) {
        UnlockChapterDialogViewModel unlockChapterViewModel = ObjectUtil.as(view.getTag(), UnlockChapterDialogViewModel.class);
        if(ObjectUtil.nonNull(unlockChapterViewModel)) {
            int     chapterId       = unlockChapterViewModel.getChapterId();
            String  chapterPrice    = unlockChapterViewModel.getBuyPriceStr();
            String  paymentType     = unlockChapterViewModel.isBeanUnlockPanel() ? "bean" : "coin";
            viewModel.unlockChapterByBuy(chapterId, chapterPrice, paymentType);
        }
    }
}
